<template>
  <div id="userLayout" class="w-full h-full relative">
    <div
      class="rounded-lg flex items-center justify-evenly w-full h-full md:w-screen md:h-screen md:bg-[#194bfb] bg-white">
      <div class="md:w-3/5 w-10/12 h-full flex items-center justify-evenly">
        <div class="oblique h-[130%] w-3/5 bg-white dark:bg-slate-900 transform -rotate-12 absolute -ml-52" />
        <!-- 分割斜块 -->
        <div class="z-[999] pt-12 pb-10 md:w-96 w-full  rounded-lg flex flex-col justify-between box-border">
          <div>
            <div class="flex items-center justify-center">

              <img class="w-24" :src="$a_config.appLogo" alt>
            </div>
            <div class="mb-9">
              <p class="text-center text-4xl font-bold">{{ $a_config.appName }}</p>
              <p class="text-center text-sm font-normal text-gray-500 mt-2.5">A management platform using Golang and Vue
              </p>
            </div>
            <el-form ref="loginForm" :model="loginFormData" :rules="rules" :validate-on-rule-change="false"
              @keyup.enter="submitForm">
              <el-form-item prop="user_name" class="mb-6">
                <el-input v-model="loginFormData.user_name" size="large" placeholder="请输入用户名" suffix-icon="user" clearable/>
              </el-form-item>
              <el-form-item prop="password" class="mb-6">
                <el-input v-model="loginFormData.password" show-password size="large" type="password"
                  placeholder="请输入密码" clearable/>
              </el-form-item>
              <el-form-item v-if="loginFormData.openCaptcha" prop="captcha" class="mb-6">
                <div class="flex w-full justify-between">
                  <el-input v-model="loginFormData.captcha" placeholder="请输入验证码" size="large" class="flex-1 mr-5" clearable/>
                  <div class="w-1/3 h-11 bg-[#c3d4f2] rounded">
                    <img v-if="picPath" class="w-full h-full" :src="picPath" alt="请输入验证码" @click="loginVerify()">
                  </div>
                </div>
              </el-form-item>
              <el-form-item class="mb-6">
                <el-button class="shadow shadow-active h-11 w-full" type="primary" size="large" @click="submitForm">登
                  录</el-button>
              </el-form-item>
              <el-form-item class="mb-6">
                <el-button class="shadow shadow-active h-11 w-full" type="primary" size="large"
                  @click="checkInit">前往初始化</el-button>

              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
      <div class="hidden md:block w-1/2 h-full float-right bg-[#194bfb]"><img class="h-full"
          src="@/assets/login_right_banner.jpg" alt="banner"></div>
    </div>
  </div>
</template>

<script setup>
import { captcha } from '@/amtf/api/user'
import { checkDB } from '@/api/initdb'
import { reactive, ref } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/use_user_store'

defineOptions({
  name: "Login",
})

const router = useRouter()
// 验证函数
const checkUsername = (rule, value, callback) => {
  if (value.length < 5) {
    return callback(new Error('请输入正确的用户名'))
  } else {
    callback()
  }
}
const checkPassword = (rule, value, callback) => {
  if (value.length < 6) {
    return callback(new Error('请输入正确的密码'))
  } else {
    callback()
  }
}

// 获取验证码
const loginVerify = async () => {
  const ele = await captcha()
  rules.captcha.push({
    max: ele.data.captchaLength,
    min: ele.data.captchaLength,
    message: `请输入${ele.data.captchaLength}位验证码`,
    trigger: 'blur',
  })
  picPath.value = ele.data.picPath
  loginFormData.captchaId = ele.data.captchaId
  loginFormData.openCaptcha = ele.data.openCaptcha
}
loginVerify()

// 登录相关操作
const loginForm = ref(null)
const picPath = ref('')
const loginFormData = reactive({
  user_name: 'admin',
  password: '',
  captcha: '',
  captchaId: '',
  openCaptcha: false,
})
const rules = reactive({
  user_name: [{ validator: checkUsername, trigger: 'blur' }],
  password: [{ validator: checkPassword, trigger: 'blur' }],
  captcha: [
    {
      message: '验证码格式不正确',
      trigger: 'blur',
    },
  ],
})

const userStore = useUserStore()
const login = async () => {
  return await userStore.LoginIn(loginFormData)
}
const submitForm = () => {
  loginForm.value.validate(async (v) => {
    if (!v) {
      // 未通过前端静态验证
      ElMessage({
        type: 'error',
        message: '请正确填写登录信息',
        showClose: true,
      })
      await loginVerify()
      return false
    }

    // 通过验证，请求登陆
    const flag = await login()

    // 登陆失败，刷新验证码
    if (!flag) {
      await loginVerify()
      return false
    }

    // 登陆成功
    return true
  })
}

// 跳转初始化
const checkInit = async () => {
  const res = await checkDB()
  if (res.code === 0) {
    if (res.data?.needInit) {
      userStore.NeedInit()
      await router.push({ name: 'Init' })
    } else {
      ElMessage({
        type: 'info',
        message: '已配置数据库信息，无法初始化',
      })
    }
  }
}

</script>
